package com.py.credit.controller;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.MulQureryEnum;
import com.py.credit.service.MulQueryService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping("/mulQuery")
public class MulQueryController {

	@Autowired
	private MulQueryService mulQueryService;
	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	private static String FRONT_TABLE_ID = "report";

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(MulQureryEnum.getOptionalColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;
	}

	@IgnoreAuthority
	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<LinkedHashMap<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = false) String condition, String orgId,
			String sqr_str, String reportType, String shzt, Page page, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] additionalColumns = { "id", "modelId", "sqr", "scoreType", "zone", "industry", "checkProcess" };
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? MulQureryEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		RestServiceResult<List<LinkedHashMap<String, Object>>> r = new RestServiceResult<>();
		try {
			List<LinkedHashMap<String, Object>> tableList = mulQueryService.getByConditionForPage(showColumns,
					additionalColumns, condition, page, orgId, sqr_str, reportType, shzt);
			r = new RestServiceResult<>(page.getTotalCount(), tableList);
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常！");
		}
		return r;
	}

	@RequestMapping(value = "/export")
	public RestServiceResult<List<LinkedHashMap<String, Object>>> exportData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, String orgId,
			String sqr_str, String reportType, String shzt, Page page, HttpServletResponse response,
			HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<LinkedHashMap<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		page.setLimit(1000);
		String[] configColumns = (String[]) MapCache.get(1000 + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? MulQureryEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		List<LinkedHashMap<String, Object>> tableList = mulQueryService.getByConditionForPage(showColumns, null,
				condition, page, orgId, sqr_str, reportType, shzt);
		try {
			ExcelUtil.downloadLinkExcel(response, tableList, "评价报告", "评价报告", showColumns,
					MulQureryEnum.getOptionalColumns());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("综合查询导出异常，请稍后再试！");
			ExceptionLogger.error("综合查询导出异常！", e.getMessage(), e);
			return result;
		}
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		RestServiceResult<List<OptionalColumn>> r = new RestServiceResult<List<OptionalColumn>>();
		try {
			r = new RestServiceResult<List<OptionalColumn>>(MulQureryEnum.getAdvancedConditionColumns());
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("系统异常");
		}
		return r;

	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("AchievementController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			String column = StringUtils.join(columns, ",");
			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}
}
